package com.xywy.wjk;



import java.text.DecimalFormat;
import java.util.List;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.xywy.R;
import com.xywy.common.app.MainApplication;
import com.xywy.common.bean.ConnectedDevice;
import com.xywy.common.greendao.BaseDao;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.ImageLoaderUtil;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;
import com.xywy.wjk.bean.BloodPressureData;
import com.xywy.wjk.bean.WeightData;
import com.xywy.wjk.dao.BloodPressureDataDao;
import com.xywy.wjk.dao.BloodPressureDataDao.Properties;
import com.xywy.wjk.dao.WeightDataDao;
import com.xywy.wjk.fragment.BloodPressureFragment;
import com.xywy.wjk.fragment.TempperatureFragment;
import com.xywy.wjk.fragment.WeightFragment;
import com.xywy.wjk.util.WjkConstant;
import com.xywy.wjk.widget.TipDialog;
import com.xywy.wjk.widget.TipDialog.CancleListener;
import com.xywy.wjk.widget.TipDialog.ConfirmListener;

import de.greenrobot.dao.query.QueryBuilder;

public class WjkActivity extends FragmentActivity implements OnClickListener{
	//蓝牙需要
	public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";
	public static final int FRAGMENT_WEIGHT_SCLAE = 0; // 体重秤
	public static final int FRAGMENT_BLOOD_PRESURE = 1; // 血压计
	public static final int FRAGMENT_TEMPU_PRESURE = 2; // 体温计
	public static final String CURRENT_FRAGMENT = "current_fragment"; // sp key；
	public static final int WEIGHT_SCALE_REQUEST_CODE = 1030; // 体重
	public static final int BLOOD_PRESURE_REQUEST_CODE = 1040; // 血压
	public static final int THERMOMETER_REQUEST_CODE = 1050; // 体温
	public static final int BLOOD_SUGAR_REQUEST_CODE = 1060; // 血糖
	protected static final String TAG = "WjkActivity";
	public static final int REQUEST_DIALOG = 0x1111; //连接设备
	//fragment 内嵌的 可能有多个
	public static int HEIGHT = 250;
	private WeightFragment weitFragment;
	private BloodPressureFragment blFragment;
	private TempperatureFragment teFragment;
//	// 新加的 里面的fragment
	private FragmentManager fragmentManager;
	private TextView ivAdd; //添加设备按钮
	//下面的是连接到不同设备
	private ImageButton btnFirst; // 第一个按钮
	private LinearLayout llFirst; // 第一个按钮
	private ImageButton btn_yjk_second; // 第二个按钮
	private ImageButton btn_yjk_third; // 第三个按钮
	private TextView tv_wjk_right_add ;// 添加设备
	
	private boolean blood_connect_status;
	private boolean weight_connect_status;
	private ImageView slidingMenuIcon;
	
	private TextView tv_last_connected_device_name;
	private TextView tv_last_connected_device_unit;
	private ImageView iv_last_connected_device_view;
	private TextView tv_last_connected_device_value;
	private BloodPressureDataDao bloodPressureDataDao;
	private WeightDataDao weightDataDao;
	private User current_user;
	
	
	//注册一个广播接受者  也就是 如果发送的广播是这个广播 那么直接去连接 某一个设备
	//否则接收到
	
	@Override
	protected void onCreate(Bundle savedinstance) {
		super.onCreate(savedinstance);
		setContentView(R.layout.fragment_wjk);
		initReceiver();
		initView();
		initDAO();
		initDialog();
		SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
		fragmentManager = getSupportFragmentManager();
		initTab();
	}
	
	private void initTab(){
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		if (weitFragment == null){
			weitFragment = new WeightFragment();
			transaction.add(R.id.innerframe, weitFragment);
		}
		if (blFragment == null){
			blFragment = new BloodPressureFragment();
			transaction.add(R.id.innerframe, blFragment);
		}
		
		if(teFragment == null){
			teFragment = new TempperatureFragment();
			transaction.add(R.id.innerframe, teFragment);
		}
		transaction.commit();

		
		ConnectedDevice connect_device = FileUtil.getCurrentDevice();
		if(connect_device.getConnect_time() ==0){
			showLastDeviceFragment(FRAGMENT_WEIGHT_SCLAE);
		}else{
			String device_name = connect_device.getDevice_name();
			if(device_name.contains(ConnectedDevice.WEIGHT_NAME)){
				showLastDeviceFragment(FRAGMENT_WEIGHT_SCLAE);
			}else if(device_name.contains(ConnectedDevice.BLOOD_NAME)){
				showLastDeviceFragment(FRAGMENT_BLOOD_PRESURE);
			}else if (device_name.contains(ConnectedDevice.TEMPUTER_NAME)) {
				showLastDeviceFragment(FRAGMENT_TEMPU_PRESURE);
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_wjk_right_add:
			MobclickAgent.onEvent(this, "A002");
			MobclickAgent.updateOnlineConfig(this);
			intentAddDevice();
			break;
		case R.id.iv_wjk_left_sliding_menu_icon:
			Intent intent = new Intent(WjkConstant.OPEN_SLIDE);
			sendBroadcast(intent);
			break;
		case R.id.btn_yjk_second:
			dialog.show();
			dialog.setTitleAndContent("体温计", "该设备尚未开启，立即前往添加？");
			dialog.setConfirmCallback(new ConfirmListener() {

				@Override
				public void confirm() {
					dialog.dismiss();
					Intent weightIntent = new Intent(WjkActivity.this, SelectBrandActivity.class);
					weightIntent.putExtra("deviceType", "体温计");
					startActivityForResult(weightIntent, THERMOMETER_REQUEST_CODE);
				}
			});
			break;
		case R.id.btn_yjk_third:
			dialog.show();
			dialog.setTitleAndContent("血糖仪", "该设备尚未开启，立即前往添加？");
			dialog.setConfirmCallback(new ConfirmListener() {

				@Override
				public void confirm() {
					dialog.dismiss();
					Intent weightIntent = new Intent(WjkActivity.this, SelectBrandActivity.class);
					weightIntent.putExtra("deviceType", "血糖仪");
					startActivityForResult(weightIntent, BLOOD_SUGAR_REQUEST_CODE);
				}
			});
			break;

		default:
			break;
		}
	}
	
	private void initView(){
		ivAdd = (TextView) findViewById(R.id.iv_wjk_right_add);
		btnFirst = (ImageButton) findViewById(R.id.btn_yjk_first);
		llFirst = (LinearLayout) findViewById(R.id.ll_yjk_first);
		btn_yjk_third = (ImageButton) findViewById(R.id.btn_yjk_third);
		btn_yjk_second = (ImageButton) findViewById(R.id.btn_yjk_second);
		tv_wjk_right_add = (TextView) findViewById(R.id.tv_wjk_right_add);
		tv_wjk_right_add.setOnClickListener(this);
		slidingMenuIcon = (ImageView) findViewById(R.id.iv_wjk_left_sliding_menu_icon);
		slidingMenuIcon.setOnClickListener(this);
		
		tv_last_connected_device_name = (TextView) findViewById(R.id.tv_last_connected_device_name);
		tv_last_connected_device_unit = (TextView) findViewById(R.id.tv_last_connected_device_unit);
		iv_last_connected_device_view = (ImageView) findViewById(R.id.iv_last_connected_device_view);
		tv_last_connected_device_value = (TextView) findViewById(R.id.tv_last_connected_device_value);
	
		btn_yjk_second.setOnClickListener(this);
		btn_yjk_third.setOnClickListener(this);
		current_user = UserKeeper.getCurrentUser(this);
		ImageLoaderUtil.displayHeadImage(current_user.getAvatar(), slidingMenuIcon);
	}
	int current = 0;
	/**
	 * 根据传入的index参数来设置选中的tab页。
	 * 
	 * @param index
	 *            每个tab页对应的下标。0表示体重秤，1表示血压计
	 */
	public void setTabSelection(int index) {
		current = index;
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		hideFragments(transaction);
		switch (index) {
		case FRAGMENT_WEIGHT_SCLAE:
			transaction.show(weitFragment);
			showBottomView(0);
			break;
		case FRAGMENT_BLOOD_PRESURE:
			transaction.show(blFragment);
			showBottomView(1);
			break;
       case FRAGMENT_TEMPU_PRESURE:
			transaction.show(teFragment);
			showBottomView(1);
			break;
		}
		transaction.commitAllowingStateLoss();
	}
	
	private void hideFragments(FragmentTransaction transaction){
		if(weitFragment != null){
			transaction.hide(weitFragment);
		}
		if(blFragment != null){
			transaction.hide(blFragment);
		}
		if(teFragment != null){
			transaction.hide(teFragment);
		}
	}
	
	/**
	 * 展示最后一次连接过的设备为大图fragment
	 */
	private void showLastDeviceFragment(int temp) {
		setTabSelection(temp); // 默认体重秤为第一页面
	}
	/**
	 * 跳转到添加设备界面
	 */
	private void intentAddDevice() {
		Intent intent = new Intent(this, AddDevicesActivity.class);
		startActivity(intent);
	}
	
	private void initReceiver(){
		IntentFilter filter = new IntentFilter(WjkConstant.DISCONNECT_ACTION_TOBLOOD);
		filter.addAction(WjkConstant.CONNECT_BLOOD_ACTION);
		filter.addAction(WjkConstant.CONNECT_WEIGHT_ACTION);
		filter.addAction(WjkConstant.CONNECT_TEMPUT_ACTION);
		filter.addAction(WjkConstant.CONNECT_BLOOD_ACTION_DISCONNET);
		filter.addAction(WjkConstant.CONNECT_WEIGHT_ACTION_DISCONNECT);
		filter.addAction(WjkConstant.CONNECT_TEMPUT_ACTION_DISCONNECT);
		filter.addAction(WjkConstant.DISCONNECT_ACTION_TOWEIGHT);
		filter.addAction(WjkConstant.DISCONNECT_ACTION_TOTEMPUT);
		filter.addAction(WjkConstant.IMAGE_URL);
		registerReceiver(new ChangeReceiver(), filter);
		  registerReceiver(mHomeKeyEventReceiver, new IntentFilter(  
	                Intent.ACTION_CLOSE_SYSTEM_DIALOGS));  
	}
	
	class ChangeReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			/**
			 * 关闭menu
			 */
			Intent closeIntent = new Intent(WjkConstant.CLOSE_SLIDE);
			sendBroadcast(closeIntent);
			
			if(WjkConstant.CONNECT_WEIGHT_ACTION.equals(action)){
				System.out.println("现在连接体重----");
				showLastDeviceFragment(FRAGMENT_WEIGHT_SCLAE);
				Intent connect_weight_intent = new Intent(WjkConstant.CONNECTING_WEIGHT_ACTION);
				sendBroadcast(connect_weight_intent);
			}else if (WjkConstant.CONNECT_BLOOD_ACTION.equals(action)){
				System.out.println("现在连接血压----");
				showLastDeviceFragment(FRAGMENT_BLOOD_PRESURE);
				Intent connect_blood_intent = new Intent(WjkConstant.CONNECTING_BLOOD_ACTION);
				sendBroadcast(connect_blood_intent);
			}else if (WjkConstant.CONNECT_TEMPUT_ACTION.equals(action)) {
				System.out.println("现在连接体温----");
				showLastDeviceFragment(FRAGMENT_TEMPU_PRESURE);
				Intent connect_blood_intent = new Intent(WjkConstant.CONNECTING_TEMPUT_ACTION);
				sendBroadcast(connect_blood_intent);
			}
			
			else if (WjkConstant.CONNECT_BLOOD_ACTION_DISCONNET.equals(action)){
				System.out.println("现在跳转到血压----");
				showLastDeviceFragment(FRAGMENT_BLOOD_PRESURE);
			}else if (WjkConstant.CONNECT_WEIGHT_ACTION_DISCONNECT.equals(action)){
				System.out.println("现在跳转到体重----");
				showLastDeviceFragment(FRAGMENT_WEIGHT_SCLAE);
			}else if (WjkConstant.CONNECT_TEMPUT_ACTION_DISCONNECT.equals(action)) {
				System.out.println("现在跳转到体温");
				showLastDeviceFragment(FRAGMENT_TEMPU_PRESURE);
			}
			
			else if (WjkConstant.DISCONNECT_ACTION_TOBLOOD.equals(action)){
				System.out.println("现在连接血压----kkkkkkzzzzzyyyyyy");
				Intent connect_blood_intent = new Intent(WjkConstant.CONNECTING_BLOOD_ACTION);
				sendBroadcast(connect_blood_intent);
			}else if(WjkConstant.DISCONNECT_ACTION_TOWEIGHT.equals(action)){
				Intent connect_weight_intent = new Intent(WjkConstant.CONNECTING_WEIGHT_ACTION);
				sendBroadcast(connect_weight_intent);
			}else if (WjkConstant.DISCONNECT_ACTION_TOTEMPUT.equals(action)) {
				System.out.println("断开后 连接体温fasdfasdfasdfasdfdfsd");
				Intent connect_weight_intent = new Intent(WjkConstant.CONNECTING_TEMPUT_ACTION);
				sendBroadcast(connect_weight_intent);
			}
			
			
			else if(WjkConstant.IMAGE_URL.equals(action)){
//				String url = intent.getStringExtra("url");
//				System.out.println("hahahhahaha "+url);
//				ImageLoaderUtil.displayHeadImage(url, slidingMenuIcon);
			}
			
		}
	}
	
	
	/**
	 * 展示底部第一个按钮的样式
	 * 
	 * @param temp
	 *            当前的fragment
	 */
	private void showBottomView(int index) {
		// 大块是体重
		if (index == FRAGMENT_WEIGHT_SCLAE) {
			ConnectedDevice weight_device = FileUtil.getWeightDevice();
			if (weight_device.getConnect_time() >0) {
				tv_last_connected_device_name.setText("血压");
				tv_last_connected_device_unit.setText("mmHg");
				iv_last_connected_device_view.setImageResource(R.drawable.bp_value);
				List<BloodPressureData> bp_lastdata = getLastData();
				if (bp_lastdata != null && bp_lastdata.size() > 0) {

					DecimalFormat df = new DecimalFormat("0");

					tv_last_connected_device_value.setText(df.format(bp_lastdata.get(0).getHighPressure()) + "~" + df.format(bp_lastdata.get(0).getLowPressure()));
				} else {
					tv_last_connected_device_value.setText("0~0");
				}
				TextView tv = (TextView) findViewById(R.id.tv_last_connected_device_value);
				TextPaint tp = tv.getPaint();
				tp.setFakeBoldText(true);

				llFirst.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(WjkActivity.this, BloodPressureDetailActivity.class);
						startActivity(intent);
					}
				});
			} else {
				llFirst.setVisibility(View.GONE);
				btnFirst.setVisibility(View.VISIBLE);
				btnFirst.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						dialog = new TipDialog(WjkActivity.this, TipDialog.VIEW_DIALOG);
						dialog.show();
						dialog.setTitleAndContent("血压仪", "该设备尚未开启，立即前往添加？");
						dialog.setCancleCallback(new CancleListener() {
							@Override
							public void cancle() {
								dialog.dismiss();

							}
						});
						dialog.setConfirmCallback(new ConfirmListener() {

							@Override
							public void confirm() {
								dialog.dismiss();
								Intent weightIntent = new Intent(WjkActivity.this, SelectBrandActivity.class);
								weightIntent.putExtra("deviceType", "血压仪");
								startActivityForResult(weightIntent, BLOOD_PRESURE_REQUEST_CODE);
							}
						});
					}
				});
			}

		} else if (index == FRAGMENT_BLOOD_PRESURE) {
			// 大块是血压
			ConnectedDevice blood_device = FileUtil.getBloodDevice();
			if (blood_device.getConnect_time() >0) {
				btnFirst.setVisibility(View.GONE);
				// btnFirst.setImageResource(R.drawable.weight_connected);
				llFirst.setVisibility(View.VISIBLE);
				tv_last_connected_device_name.setText("体重");
				tv_last_connected_device_unit.setText("kg");
				iv_last_connected_device_view.setImageResource(R.drawable.weight_value);
				WeightData weight = getLastWeightData();
				if (weight != null) {
					tv_last_connected_device_value.setText(weight.getWeight() + "");

				} else {
					tv_last_connected_device_value.setText("00.0");
				}
				TextPaint tp = tv_last_connected_device_value.getPaint();
				tp.setFakeBoldText(true);

				llFirst.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(WjkActivity.this, WjkDetailActivity.class);
						intent.putExtra("current", current);
						startActivity(intent);
					}
				});
			} else {
				// btnFirst.setVisibility(View.VISIBLE);
				llFirst.setVisibility(View.GONE);
				btnFirst.setVisibility(View.VISIBLE);
				// btnFirst.setImageResource(R.drawable.weight_not_open);
				btnFirst.setBackground(getResources().getDrawable(R.drawable.weight_not_open));
				btnFirst.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						dialog.show();
						dialog.setTitleAndContent("体质称", "该设备尚未开启，立即前往添加？");
						dialog.setConfirmCallback(new ConfirmListener() {
							@Override
							public void confirm() {
								dialog.dismiss();
								Intent weightIntent = new Intent(WjkActivity.this, SelectBrandActivity.class);
								weightIntent.putExtra("deviceType", "体重秤");
								startActivityForResult(weightIntent, BLOOD_PRESURE_REQUEST_CODE);
							}
						});
					}
				});
			}
		}

	}
	
	
	/* 初始化DAO 需要获取最后一次的数据，并且展示在底部按钮上 */
	private void initDAO() {
		BaseDao baseDao = BaseDao.getInstance(this);
		bloodPressureDataDao = baseDao.getBloodPressureDataDao();
		weightDataDao = baseDao.getWeightDataDao();
	}
	/**
	 * 获取最后一条数据
	 * 
	 * @return
	 */
	private List<BloodPressureData> getLastData() {
		QueryBuilder<BloodPressureData> qb = bloodPressureDataDao.queryBuilder();
		qb.where(Properties.User_id.eq(current_user.getUserid()));
		qb.orderDesc(Properties.Id);
		return qb.list();
	}

	/**
	 * 获取最后一条数据；
	 */
	private WeightData getLastWeightData() {
		QueryBuilder<WeightData> qb = weightDataDao.queryBuilder();
		qb.where(WeightDataDao.Properties.User_id.eq(current_user.getUserid()));
		qb.orderDesc(WeightDataDao.Properties.Id);
		List<WeightData> list = qb.list();
		if (list != null && list.size() > 0) {
			return list.get(0);
		} else {
			return null;
		}
	}
	TipDialog dialog ;
	/**
	 * 为当前Dialog做事件处理，并且判断是否第一次使用。
	 */
	private void initDialog() {
		boolean isBind =  false;
		ConnectedDevice blood_device = FileUtil.getBloodDevice();
		ConnectedDevice weight_device = FileUtil.getWeightDevice();
		if(blood_device.getConnect_time() ==0&& weight_device.getConnect_time()==0){
			isBind = false;
		}else {
			isBind = true;
		}
		if (dialog == null) {
			dialog = new TipDialog(this, TipDialog.VIEW_DIALOG);
		}
		/* 当设备未开启的时候，点击体重未开启后提示： */
		dialog.setTitleAndContent("欢迎来到云健康", "立即前往添加设备吧");
		/**
		 * 获取内部Dialog 实例； 并且监听他的消失方法；
		 */
		Dialog dialogInstance = dialog.getDialog();
		dialogInstance.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface arg0) {
				MainApplication.setFirstOpenAPp(false);
			}
		});
		if (!isBind && MainApplication.isFirstOpenAPp()) {
//			dialog.show();
			Intent intent = new Intent(this,WjkPopupActivity.class);
			startActivityForResult(intent, REQUEST_DIALOG);
		}

		dialog.setCancleCallback(new CancleListener() {
			@Override
			public void cancle() {
				dialog.dismiss();

			}
		});
		/**
		 * 点击确定后，不同的状态进入不同的
		 */
		dialog.setConfirmCallback(new ConfirmListener() {
			@Override
			public void confirm() {
				intentAddDevice();
				if (dialog != null) {
					dialog.dismiss();
				}
			}
		});
		
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		System.out.println("onActivityResult----wjkfragment");
		if(data != null && resultCode == RESULT_OK)
		switch (requestCode) {
		case REQUEST_DIALOG:
			int confirm = data.getIntExtra("confirm", -1);
			if(confirm == 1){
				intentAddDevice();
			}
			break;
		default:
			break;
		}
	}
	
	
	public static boolean HOME_FLAG = false;
    private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() {  
        String SYSTEM_REASON = "reason";  
        String SYSTEM_HOME_KEY = "homekey";  
        String SYSTEM_HOME_KEY_LONG = "recentapps";  
           
        @Override  
        public void onReceive(Context context, Intent intent) {  
            String action = intent.getAction();  
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {  
                String reason = intent.getStringExtra(SYSTEM_REASON);  
                if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) {  
                     //表示按了home键,程序到了后台  
                    HOME_FLAG = true;
                }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){  
                    //表示长按home键,显示最近使用的程序列表  
                }  
            }   
        }  
    };  
	
}
